package com.dream.xiaobo.filter;

import com.dream.xiaobo.entity.User;
import com.dream.xiaobo.service.impl.UserServiceImpl;
import com.dream.xiaobo.utils.Base64Utils;
import com.dream.xiaobo.utils.Constants;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/** 自动登录过滤器
 * @author xiaobo
 * @date 2021/8/30 - 20:59
 */
@WebFilter("/login.jsp")
public class AutoFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //转换类型
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //转换类型
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取浏览器中的所有Cooke
        Cookie[] cookies = request.getCookies();
        //当浏览器中有Cooke记录时
        if(cookies != null){
            //定义一个变量
            String content = null;
            //遍历获得到的所有Cooke
            for (Cookie cookie : cookies){
                //拿到登录保存的Cooke的名字
                if (cookie.getName().equals(Constants.AUTO_NAME)) {
                    //拿到登录保存的Cooke值
                    content = cookie.getValue();
                }
            }
            //当拿到的值不为空时
            if(content != null){
                //用Bese64还原一下
                content = Base64Utils.decode(content);
                //将拿到的值拆分一下、存到数组中
                String[] split = content.split(Constants.FLAG);
                //获取到用户名
                String username = split[0];
                //获取到密码
                String password = split[1];
                //创建UserServiceImpl实例化对象
                UserServiceImpl userService = new UserServiceImpl();

                try {
                    //调用登录逻辑
                    User user = userService.loginUser(username, password);
                    //当user对象不为空时
                    if(null != user){
                        //将信息存放到Session中
                        request.getSession().setAttribute("loginUser",user);
                        //重定向、首页
                        response.sendRedirect(request.getContextPath() + "/index.jsp");
                    }else{
                        //放行
                        filterChain.doFilter(request,response);
                    }
                //异常处理
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }else{
                //放行
                filterChain.doFilter(request,response);
            }
        }else{
            //放行
            filterChain.doFilter(request,response);
        }
    }

    @Override
    public void destroy() {

    }
}
